<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入用户昵称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="用户手机" prop="mobile">
        <el-input v-model="queryParams.mobile" placeholder="请输入用户手机" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="用户积分" prop="points">
        <el-input v-model="queryParams.points" placeholder="请输入用户积分" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['wechat:user:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['wechat:user:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['wechat:user:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['wechat:user:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键编号" align="center" prop="id"/>
      <el-table-column label="用户昵称" align="center" prop="nickName"/>
      <el-table-column label="用户头像" align="center" prop="avatar">
        <template slot-scope="scope">
          <el-image v-if="scope.row.avatar !== '' && scope.row.avatar !== null && scope.row.avatar !== undefined"
                    style="border-radius: 50%;width: 40px;height: 40px;cursor: pointer"
                    :src="scope.row.avatar" fit="cover" :preview-src-list="[scope.row.avatar]"
          />
        </template>
      </el-table-column>
      <el-table-column label="用户手机" align="center" prop="mobile"/>
      <el-table-column label="用户积分" align="center" prop="points"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['wechat:user:edit']">修改</el-button>
            </el-col>
            <el-col :span="12">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['wechat:user:remove']">删除</el-button>
            </el-col>
            <el-col :span="12">
              <el-button size="mini" type="text" icon="el-icon-medal" @click="handlePoints(scope.row)" v-hasPermi="['wechat:user:points']">派送积分</el-button>
            </el-col>
            <el-col :span="12">
              <el-button size="mini" type="text" icon="el-icon-tickets" @click="openPointsRecord(scope.row)" v-hasPermi="['wechat:points:record']">积分记录</el-button>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改微信用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="40%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="用户头像" prop="avatar">
              <ImageUpload v-model="form.avatar" :limit="1"></ImageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="50" show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户手机" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入用户手机" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户积分" prop="points">
              <el-input-number v-model="form.points" :precision="0" :min="0" label="用户积分"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改积分对话框 -->
    <el-dialog title="修改积分" :visible.sync="pointsOpen" width="40%" append-to-body>
      <el-form ref="pointsForm" :model="pointsForm" :rules="pointsRules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="操作类型" prop="type">
              <el-radio-group v-model="pointsForm.type">
                <el-radio-button label="1">增加</el-radio-button>
                <el-radio-button label="2">减少</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户积分" prop="points">
              <el-input-number v-model="pointsForm.points" :precision="0" :min="0" label="用户积分"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPointsForm">确 定</el-button>
        <el-button @click="cancelPointsForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 积分记录 -->
    <el-dialog title="积分记录" :visible.sync="pointsRecordOpen" width="60%" append-to-body>
      <el-table v-loading="recordLoading" :data="recordList">
        <el-table-column label="用户昵称" align="center" prop="userName"/>
        <el-table-column label="派送前积分" align="center" prop="beforePoints"/>
        <el-table-column label="派送积分" align="center" prop="points"/>
        <el-table-column label="派送后积分" align="center" prop="afterPoints"/>
        <el-table-column label="派送人" align="center" prop="createByName"/>
        <el-table-column label="派送时间" align="center" prop="createTime" width="180"/>
        <el-table-column label="描述" align="center" prop="desc"/>
      </el-table>
      <pagination v-show="recordTotal>0" :total="recordTotal" :page.sync="recordQueryParams.pageNum" :limit.sync="recordQueryParams.pageSize" @pagination="getRecordList"/>
    </el-dialog>
  </div>
</template>

<script>
import {addUser, delUser, getUser, listUser, setPoints, updateUser} from '@/api/wechat/wechatUser'
import ImageUpload from '@/components/ImageUpload'
import {listRecord} from "@/api/wechat/pointsRecord";

export default {
  components: {ImageUpload},
  name: 'wechatUser',
  data() {
    const validMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      } else {
        const reg = /^1[3456789]\d{9}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      }
    }
    return {
      loading: true,                                                        // 遮罩层
      ids: [],                                                              // 选中数组
      single: true,                                                         // 非单个禁用
      multiple: true,                                                       // 非多个禁用
      showSearch: true,                                                     // 显示搜索条件
      total: 0,                                                             // 总条数
      userList: [],                                                         // 微信用户表格数据
      title: '',                                                            // 弹出层标题
      open: false,                                                          // 是否显示弹出层
      queryParams: {                                                        // 查询参数
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        mobile: null,
        points: null,
        releaseNewsNum: null
      },
      form: {                                                               // 表单参数
      },
      rules: {                                                              // 表单校验
        nickName: [{required: true, message: '请输入用户昵称', trigger: 'blur'}],
        mobile: [{required: true, message: '请输入用户手机', trigger: 'blur'}, {validator: validMobile, trigger: 'blur'}]
      },
      pointsOpen: false,                                                    // 修改积分开关
      pointsForm: {                                                         // 积分表单
      },
      pointsRules: {                                                        // 积分表单校验
        type: [{required: true, message: '请选择操作类型', trigger: 'blur'}],
        points: [{required: true, message: '请输入积分', trigger: 'blur'}]
      },
      pointsRecordOpen: false,
      recordLoading: true,
      recordList: [],
      // 查询参数
      recordQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        beforePoints: null,
        points: null,
        afterPoints: null,
        desc: null,
      },
      // 总条数
      recordTotal: 0,
    }

  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询微信用户列表 */
    getList() {
      this.loading = true
      listUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        nickName: null,
        avatar: null,
        mobile: null,
        points: null,
        openId: null,
        releaseNewsNum: null,
        createTime: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加微信用户'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改微信用户'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除微信用户编号为"' + ids + '"的数据项？').then(function () {
        return delUser(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 修改积分操作 */
    handlePoints(row) {
      this.resetPointsForm()
      const id = row.id || this.ids
      getUser(id).then(response => {
        let user = response.data
        this.pointsForm.originalPoints = user.points
        this.pointsForm.userId = user.id
        this.pointsForm.points = 0
        this.pointsOpen = true
      })
    },
    /** 积分表单重置操作 */
    resetPointsForm() {
      this.pointsForm = {
        originalPoints: null,
        userId: null,
        points: null,
        type: null,
      }
      this.resetForm('pointsForm')
    },
    /** 提交按钮 */
    submitPointsForm() {
      if (this.pointsForm.type === 2 || this.pointsForm.type === '2') {
        if (this.pointsForm.points > this.pointsForm.originalPoints) {
          this.$modal.msgWarning("减少的积分不可以超过用户原积分")
          return
        }
      }
      this.$refs['pointsForm'].validate(valid => {
        if (valid) {
          setPoints(this.pointsForm).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.pointsOpen = false
            this.getList()
          })
        }
      })
    },
    /** 取消修改积分操作 */
    cancelPointsForm() {
      this.pointsOpen = false
      this.resetPointsForm()
    },

    /** 打开积分记录操作 */
    openPointsRecord(row) {
      this.pointsRecordOpen = true
      this.recordQueryParams.userId = row.id
      this.getRecordList()
    },

    /** 查询微信用户积分记录列表 */
    getRecordList() {
      this.recordLoading = true;
      listRecord(this.recordQueryParams).then(response => {
        this.recordList = response.rows;
        this.recordTotal = response.total;
        this.recordLoading = false;
      });
    },
  }
}
</script>
